/**
 * 
 */
package cn.ehuoyuan.shop.action.pay;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeRefundRequest;

import cn.ehuoyuan.common.CommomUtils;
import cn.ehuoyuan.common.Tools;
import cn.ehuoyuan.shop.action.frontShow.OrderPay;
import cn.ehuoyuan.shop.service.pay.PayService;

/**
 * 支付Action,主要处理退款申请
 * @author liandyao
 * @date 2018年7月19日
 * @version 1.0
 */
@Controller
@RequestMapping("/payAction")
public class PayAction {

	@Resource
	PayService payService ;
	
	Logger logger = Logger.getLogger(AlipayAction.class);

	/**
	 * 退款申请
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping("refund")
	public void refund(HttpServletRequest request,HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		//设置请求参数
		AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
		//得到订单ID
		String ordId = request.getParameter("ordId");
		//得到退款金额
		String money = request.getParameter("money");
		OrderPay order = payService.getOrder(ordId);
		//logger.info("退款申请,支付方式:"+order.getPayType());
		if(CommomUtils.PAY_TYPE_ALIPAY.equals(order.getPayType())) {
			//商户订单号，商户网站订单系统中唯一订单号
			String out_trade_no = ordId;
			//支付宝交易号
			String trade_no = "";
			//请二选一设置
			//需要退款的金额，该金额不能大于订单金额，必填
			//微信支付和支付宝支付的区别是,微信支付回调的值是分为单位,而支付宝则是元为单位
			String refund_amount = money; 
			//退款的原因说明
			String refund_reason = "ehuoyuan买家发起支付宝退款申请!";
			//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
			String out_request_no = ordId+"_"+refund_amount;
			
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
					+ "\"trade_no\":\""+ trade_no +"\"," 
					+ "\"refund_amount\":\""+ refund_amount +"\"," 
					+ "\"refund_reason\":\""+ refund_reason +"\"," 
					+ "\"out_request_no\":\""+ out_request_no +"\"}");
			
			//请求
			String result = "{\"alipay_trade_refund_response\":{\"code\":\"-1\",\"msg\":\"Error\"}}";
			try {
				result = AlipayAction.alipayClient.execute(alipayRequest).getBody();
				//logger.info("=====================result============"+result);
			} catch (AlipayApiException e) { 
				e.printStackTrace();
			}
			
			//输出
			out.println(result);
		}else if(CommomUtils.PAY_TYPE_WXPAY.equals(order.getPayType())) {
			Map<String, String> data = new HashMap<String, String>();
	        data.put("out_trade_no", ordId);
	        data.put("out_refund_no", ordId);
	        //微信支付和支付宝支付的区别是,微信支付回调的值是分为单位,而支付宝则是元为单位
	        BigDecimal big = new BigDecimal(order.getPayMoneyFen());
	         
	        data.put("total_fee", big.intValue()+"");
	        
	        data.put("refund_fee", Tools.moneyYuanToFen(money));//页面上传过来的是元,转为分
	        
	        data.put("refund_fee_type", "CNY");
	        data.put("op_user_id", WxPayAction.config.getMchID());
	        String result = "{\"alipay_trade_refund_response\":{\"code\":\"-1\",\"msg\":\"Error\"}}";
	        try {
	            Map<String, String> r = WxPayAction.wxpay.refund(data);
	            //logger.info(order.getPayMoneyFen()+"=====result=======>"+r);
	            //{transaction_id=4200000135201807191664812232, nonce_str=FVlkUiuzwI4FaKEl, out_refund_no=20180719205230x5gqs8xiam, sign=79E076AEF61BD57D6C46994C8F5DE5377E4F91B274E73B5D71C9D36C8195E2A9, return_msg=OK, mch_id=1491576502, refund_id=50000007432018071905466110827, cash_fee=1, out_trade_no=20180719205230x5gqs8xiam, coupon_refund_fee=0, refund_channel=, appid=wx291dcc1ea85e0755, refund_fee=1, total_fee=1, result_code=SUCCESS, coupon_refund_count=0, cash_refund_fee=1, return_code=SUCCESS}
	            if(r.get("return_code")!=null && r.get("return_code").equals("FAIL")) {
	            	out.println(result);
	            	return ;
	            }
	            result = "{\"alipay_trade_refund_response\":{\"code\":\"10000\",\"msg\":\"Success\"}}";
	            out.println(result);
	            
	            return ;
	        } catch (Exception e) {
	            e.printStackTrace();
	           
	        }
	        out.println(result);
		}
		
		
	}
}
